using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using DBComponent;
using SigmaStock_Components;

namespace project
{
    public partial class SellMagazine : Form
    {
        OleDbConnection conn;
        OleDbCommand command;
        string query;
        int max_qty;
        List<string> magazine_names ;
        List<string> ret_names;
        AutoCompleteStringCollection mag_namesCollection=new AutoCompleteStringCollection();
        AutoCompleteStringCollection ret_namesCollection=new AutoCompleteStringCollection() ;
        public SellMagazine()
        {
            InitializeComponent();
            magazine_names = null;
            ret_names = null;
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
            dbconnection();
            if (Form3.retailer_purchaselist.Count > 0)
            {
                dataGridView1.Visible = true;
                InsertIntoTemp();
                Retailer_DBClass obj = Form3.retailer_purchaselist[0];
                this.textBox3.Text = obj.RNAME;
                textBox3.ReadOnly = true;
            }

            textBox2.Focus();
          
            currdate();
        }

        private void InsertIntoTemp()
        {
            try
            {
                query = "delete * from temp;";

                command.CommandText = query;
                command.Connection = conn;
                command.ExecuteNonQuery();
                int sno = 0;
                foreach (Retailer_DBClass obj in Form3.retailer_purchaselist)
                {
                    sno++;
                    query = "insert into temp(SNO,MNAME,MDATE,MPRICE,QTY,TOTAL) VALUES('" + sno + "','" + obj.MNAME + "','" + obj.MDATE + "','" + obj.price + "','" + obj.qty + "','" + (obj.price * obj.qty) + "');";
                    command.CommandText = query;
                    command.ExecuteNonQuery();
                }
                String s;
                s = "Select * from temp";
                OleDbCommand cmd1 = new OleDbCommand(s, conn);
                OleDbDataAdapter da = new OleDbDataAdapter(s, conn);
                DataSet ds = new DataSet();
                da.Fill(ds, "temp");
                dataGridView1.DataSource = ds;
                dataGridView1.DataMember = "temp";
                tempBindingSource.ResetBindings(false);
                this.Refresh();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        private void currdate()
        {
            label8.Text = DateTime.Now.ToString();

        }

        public void dbconnection()
        {
            conn = Mag_DealerDB.dbconnection();
            conn.Open();
            command = new OleDbCommand();
            command.Connection = conn;
        }


        private void button2_Click(object sender, EventArgs e)
        {
            if (SellMagazine_InitialValidate())
            {
                UpdateFormDetails();

            }
            


        }

        private bool SellMagazine_InitialValidate()
        {
            //to check if mag_name is not empty
            //to see if it is present in database            
            //to see if  publisher sells magazine
            //to see quantity is not empty and is positive
            bool flag = true;


            if (String.IsNullOrEmpty(textBox2.Text) || !(Validation.IsAlphaNumeric(textBox2.Text)))
            {
                Console.Beep();
                textBox7.Text = "Check magazine name";
                return false;
            }
        

            //see if quantity is not empty and positive
            if (String.IsNullOrEmpty(textBox4.Text) || !(Validation.IsPositiveNumber(textBox4.Text)))
            {
                Console.Beep();
                textBox7.Text = "Enter the quantity";
                return false;
            }


            if (String.IsNullOrEmpty(textBox3.Text) || !(Validation.IsAlphaNumeric(textBox3.Text)))
            {
                Console.Beep();
                textBox7.Text = "Check Retailer Name";
                return false;
            }

            if (magazine_names == null)
            {
                magazine_names = new List<string>();
                query = "select MNAME from magazine;";
                command.CommandText = query;
                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    magazine_names.Add(reader[0].ToString());
                }
                reader.Close();
            }

            if (!(magazine_names.Contains(textBox2.Text)))
            {
                Console.Beep();
                textBox7.Text = "Magazine name not present in database";
                return false;
            }



            if (ret_names == null)
            {
                ret_names = new List<string>();
                query = "select RNAME from retailer;";
                command.CommandText = query;
                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    ret_names.Add(reader[0].ToString());
                }
                reader.Close();
            }

            if (!(ret_names.Contains(textBox3.Text)))
            {
                Console.Beep();
                textBox7.Text = "Retailer name not present in database";
                return false;
            }




            return flag; 
        }

        private bool SellMagazine_FinalValidate()
        {

            //Check if MDATE is selected
            if (comboBox1.SelectedItem == null)
            {
                Console.Beep();
                textBox7.Text = "Check Magazine Date";
                return false;
            }

            


            return true;
        }

        private bool Check_DateComboBoxFilled()
        {
            if (comboBox1.SelectedItem==null)
            {
                Console.Beep();
                textBox7.Text = "Please select the magazine date";
                return false;
            }

            return true;
        }

        public void UpdateFormDetails()
        {
            String mname = textBox2.Text;
            string rname=textBox3.Text;

            try
            {
                string query = "select PRICE from magazine_retailer where MNAME= '" + mname + "' and RNAME = '" + rname + "';";
                OleDbCommand command = new OleDbCommand(query, conn);
                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    //textBox3.Text = reader[0].ToString();
                    textBox5.Text = reader[0].ToString();

                }
                reader.Close();
                query = "select MDATE from stock_date where MNAME='" + mname + "'; ";
                command.CommandText = query;
                reader = command.ExecuteReader();

                while (reader.Read())
                {
                    DateTime mdate = DateTime.Parse(reader[0].ToString());
                    if(!(comboBox1.Items.Contains(mdate.ToString("dd/MMM/yyyy"))))
                         comboBox1.Items.Add(mdate.ToString("dd/MMM/yyyy"));
                   // comboBox1.Items.Add(mdate.ToString());

                }
                reader.Close();

                query = "SELECT TOP 1 * from stock_date Order By T_NO DESC";
                command.CommandText = query;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    max_qty = int.Parse(reader[0].ToString());

                }
                reader.Close();
                int total = int.Parse(textBox5.Text) * int.Parse(textBox4.Text);
                textBox6.Text = total.ToString();

        

            }
            catch (Exception ex)
            {  }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (SellMagazine_InitialValidate() && check_quantity())
            {
                if (Check_DateComboBoxFilled())
                {
                    UpdateFormDetails();
                    UpdatePurchaseList();
                    Program.Invoke(this, "project.SellMagazine");
                }
            }
        }
        
        
        private void UpdatePurchaseList()
        {
            Retailer_DBClass obj = new Retailer_DBClass();
            obj.MNAME = this.textBox2.Text;
            obj.RNAME = textBox3.Text;
            obj.price = int.Parse(textBox5.Text);
            obj.qty = int.Parse(textBox4.Text);
            //DateTime d = new DateTime(dateTimePicker2.Value.Year, dateTimePicker2.Value.Month, dateTimePicker2.Value.Day);
            obj.MDATE = DateTime.Parse(comboBox1.Text);
            Form3.retailer_purchaselist.Add(obj);
        }

        private void SellMagazine_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (Application.OpenForms.Count == 1)
            {
                Program.main_form.Show();
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (textBox2.Text.Equals("")  && textBox4.Text.Equals("")&&(Form3.retailer_purchaselist.Count > 0))
            {
                Program.InvokeModal(this, "project.Payment_Retailer");
            }
            else if (SellMagazine_InitialValidate())
            {
                UpdateFormDetails();
                if (SellMagazine_FinalValidate() && check_quantity())
                {
                    if (Check_DateComboBoxFilled())
                    {
                        
                        UpdatePurchaseList();
                        Program.InvokeModal(this, "project.Payment_Retailer");
                    }

                }


            }
        }
      

        private bool check_quantity()
        {
            string mname = textBox2.Text;
            //string dt=comboBox1.Text;
            DateTime dt = new DateTime();
            dt = DateTime.Parse(comboBox1.Text);
                String qty_available = "";

                string query = "select CLOSING_STOCK from stock_date where MNAME='" + mname + "' and (((stock_date.MDATE)=#" + dt.ToString() +"#));";
                OleDbCommand command = new OleDbCommand(query,conn);
                OleDbDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    qty_available = reader[0].ToString();
                }
                reader.Close();

                if (int.Parse(qty_available) < int.Parse(textBox4.Text))
                {
                    Console.Beep();
                    MessageBox.Show("Only " + qty_available + " Magazines are Available !!!");
                    textBox4.Text = "";
                    return false;
                }
                else
                   return true;
        }

        private void SellMagazine_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'mag_dealerDataSet.temp' table. You can move, or remove it, as needed.
            this.tempTableAdapter.Fill(this.mag_dealerDataSet.temp);
           
                dbconnection();
                OleDbDataReader reader;
                command.CommandText = "select MNAME from stock_date ;";
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    if(!(mag_namesCollection.Contains(reader[0].ToString())))
                    {
                        mag_namesCollection.Add(reader[0].ToString());
                    }
                }
                reader.Close();
                textBox2.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                textBox2.AutoCompleteSource = AutoCompleteSource.CustomSource;
                textBox2.AutoCompleteCustomSource = mag_namesCollection;

                query = "select RNAME from retailer;";
                command.CommandText = query;
                reader = command.ExecuteReader();
                while (reader.Read())
                {
                    ret_namesCollection.Add(reader[0].ToString());
                }

                reader.Close();
                textBox3.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
                textBox3.AutoCompleteSource = AutoCompleteSource.CustomSource;
                textBox3.AutoCompleteCustomSource = ret_namesCollection;
                
               
                
                
            
           
        }

        private void button4_Click(object sender, EventArgs e)
        {
            textBox2.Text = "";
            textBox3.Text = "";
            textBox4.Text = "";
            textBox5.Text = "";
            textBox6.Text = "";
            textBox7.Text = "";
            comboBox1.SelectedItem = null;
            comboBox1.Items.Clear();
        }


    }
}